import api from '@/odoorpc'
import { try_call } from '@/odoorpc/tools'

function sleep(millisecond) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve()
    }, millisecond)
  })
}

export default {
  components: {},
  mixins: [],
  props: {
    action: { type: String, default: undefined },
    actionIds: { type: Array, default: () => [] }
  },
  data() {
    return {
      view: undefined, // 对象, 接口函数的入口

      viewInfo: {},
      fields: {}, // 模型的字段信息

      record: {},
      values: {},

      formValues: {}, // 编辑页面用
      editable: false // 编辑状态
    }
  },
  computed: {
    title() {
      if (this.view) {
        const action_info = this.view.action_info
        return action_info.name
      } else {
        return ''
      }
    },

    arch_buttons() {
      if (!this.view) {
        return []
      }

      return this.view.arch_buttons(this.record, this.values)
    },

    dataInfo() {
      return { record: this.record, values: this.values }
    },

    rules_edit() {
      // console.log(this.fields)

      return Object.values(this.fields).reduce((acc, meta) => {
        if (meta.required) {
          const required =
            typeof meta.required === 'function'
              ? meta.required({
                  record: { ...this.record, ...this.values }
                })
              : meta.required

          if (required) {
            acc[meta.name] = [
              { required: true, message: '不能为空!', trigger: ['change'] }
            ]
          }
        }
        return acc
      }, {})
    }
  },

  watch: {},

  async created() {},

  async mounted() {},

  methods: {
    async init() {
      // api
      console.log('init', this.action, this.actionIds)

      const view = api.env.wizardview(this.action, {
        active_ids: this.actionIds
      })
      this.view = view
      console.log('init', view)

      this.fields = await view.load_fields()
      console.log('init', this.fields, view)
      this.viewInfo = view.view_info

      await sleep(10)

      await this.load_relation()

      const dataInfo = await view.onchange_new()
      const { values } = dataInfo
      console.log('init', dataInfo)

      this.formValues = values
      this.record = {}
      this.values = values
      await this.load_relation_data(true)
      this.editable = true
    },

    async load_relation() {
      // 自定义 a-form-model
      if (this.$refs.refForm) {
        if (this.$refs.refForm.load_relation) {
          await this.$refs.refForm.load_relation()
        }
      }

      // 对于自定义 页面
      // realtion field 必须 定义 ref 参数
      // 且命名为 以 refRelation 开头 如: refRelation_child_ids
      const refRelations = Object.keys(this.$refs).filter(
        item => item.slice(0, 11) === 'refRelation'
      )

      for (const strRef of refRelations) {
        const ref = this.$refs[strRef]

        if (ref) {
          await ref.load_relation()
        }
      }

      const refFields = this.$refs.refField || []
      for (const refField of refFields) {
        await refField.load_relation()
      }
    },

    async load_relation_data(for_new) {
      if (this.$refs.refForm) {
        if (this.$refs.refForm.load_relation_data) {
          await this.$refs.refForm.load_relation_data(for_new)
        }
      }

      const refRelations = Object.keys(this.$refs).filter(
        item => item.slice(0, 11) === 'refRelation'
      )

      for (const strRef of refRelations) {
        const ref = this.$refs[strRef]

        if (ref) {
          await ref.load_relation_data(for_new)
        }
      }

      const refFields = this.$refs.refField || []
      for (const refField of refFields) {
        await refField.load_relation_data(for_new)
      }
    },

    invisible_get(meta = {}) {
      return typeof meta.invisible === 'function'
        ? meta.invisible({ record: { ...this.record, ...this.values } })
        : meta.invisible
    },

    async button_click(btn) {
      console.log(btn)

      // await sleep(1000)

      const { error, result } = await try_call(async () => {
        return await this.view.wizard_button_clicked({
          ...btn
        })
      })

      if (error) {
        console.log('btn click2 error', [error, result])
        this.$error({ title: '用户错误', content: error.data.message })
      } else {
        // if (!result) {
        //   const res_id = this.record.id
        //   this.load_data(res_id)
        // } else {
        //   console.log('todo ret action')
        //   // this._action_return(result)
        // }
      }
    },

    // 任何字段 change时 触发
    async handleChange(fname, value, value_for_write) {
      console.log('handleChange', fname, value)
      // const validate = async (done, { formValues, values }) => {
      //   this.formValues = { ...this.formValues, ...formValues }
      //   this.values = { ...this.values, ...values }
      //   await sleep(100)
      //   this.$refs.refForm.validate(async valid => {
      //     // console.log('form valid', valid)
      //     done(valid)
      //   })
      // }
      // const result = await this.view.onchange(fname, {
      //   value,
      //   value_for_write,
      //   validate
      // })
      // // console.log('handleChange ok', fname, value, result)
      // const { values: values2 = {} } = result
      // this.values = values2
      // this.formValues = { ...this.formValues, ...values2 }
    }
  }
}
